<template>
  <el-container class="layout">
    <el-header class="topbar">
      <div class="brand">职位管理</div>
      <div class="spacer"></div>
      <div class="user-info" ref="userAreaRef">
        <a class="gray-text">招聘数据 </a>
        <a class="gray-text">我的客服 </a>
        <a class="gray-text">账号权益 </a>
        <a class="gray-text">升级VIP </a>
        <span 
          class="user-name"
          :class="{ active: showUserCard }"
          @click="toggleUserCard"
        >
          {{ user.name || '用户' }}
        </span>
        <el-avatar :size="36" :src="user.avatar" @click="toggleUserCard" style="cursor: pointer;" />

        <div v-if="showUserCard" class="user-card" ref="userCardRef">
          <div class="user-card-header">
            <el-avatar :size="44" :src="user.avatar" />
            <div class="uc-head">
              <div class="uc-name">{{ user.name || '用户' }}</div>
              <div class="uc-pos">{{ user.position || '—' }}</div>
            </div>
            <div class="uc-company" @click="goCompanyInfo($event)" v-if="companyInfo">
              <span class="uc-company-text">所属企业</span>
              <svg viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg" class="uc-arrow">
                <path d="M9 18L15 12L9 6" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
              </svg>
            </div>
          </div>
          <div class="user-card-body">
            <div class="uc-item" @click="goAccount">账号设置</div>
            <div class="uc-item" @click="goSecurity">安全设置</div>
            <div class="uc-item uc-item-row" @click="goEnterprise">
              <span>企业认证</span>
              <span class="uc-status" :class="{ ok: verified, pending: !verified }">
                <template v-if="verified">
                  <svg viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg" class="uc-icon">
                    <path d="M20 6L9 17L4 12" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                  </svg>
                  已认证
                </template>
                <template v-else>
                  未认证
                </template>
              </span>
            </div>
          </div>
          <div class="user-card-footer">
            <div class="uc-logout" @click="logout">退出登录</div>
          </div>
        </div>
      </div>
    </el-header>
    <el-container>
      <el-aside width="200px" class="sidebar">
        <el-menu default-active="jobs" class="el-menu-vertical-demo" @select="handleMenuSelect">
          <el-menu-item index="jobs">职位管理</el-menu-item>
          <el-menu-item index="recommend">推荐牛人</el-menu-item>
          <el-menu-item index="search">搜索牛人</el-menu-item>
          <el-menu-item index="chat">沟通</el-menu-item>
          <el-menu-item index="intention">意向沟通</el-menu-item>
          <el-menu-item index="interact">互动</el-menu-item>
          <el-menu-item index="talent">牛人管理</el-menu-item>
          <el-menu-item index="props">道具</el-menu-item>
          <el-menu-item index="tools">工具箱</el-menu-item>
          <el-menu-item index="stats">数据统计</el-menu-item>
          <el-menu-item index="more">更多</el-menu-item>
        </el-menu>
      </el-aside>
      <el-main class="content">
        <div class="content-header">
          <el-button type="primary" @click="openPublishDialog">发布职位</el-button>
        </div>
        <el-dialog 
          v-model="publishVisible" 
          title="发布职位" 
          width="720px" 
          destroy-on-close
          class="job-dialog"
        >
          <el-form :model="form" :rules="rules" ref="formRef" label-width="110px" class="job-form">
            <el-form-item label="职位名称" prop="title">
              <el-input v-model="form.title" placeholder="例如：前端开发工程师" />
            </el-form-item>
            <el-form-item label="工作城市" prop="work_city">
              <el-input v-model="form.work_city" placeholder="例如：北京" />
            </el-form-item>
            <el-form-item label="薪资范围" prop="salary_range">
              <el-select v-model="form.salary_range" placeholder="请选择">
                <el-option label="3k以下" value="3k以下" />
                <el-option label="3-5k" value="3-5k" />
                <el-option label="5-10k" value="5-10k" />
                <el-option label="10-15k" value="10-15k" />
                <el-option label="15-20k" value="15-20k" />
                <el-option label="20-30k" value="20-30k" />
                <el-option label="30-50k" value="30-50k" />
                <el-option label="50k以上" value="50k以上" />
              </el-select>
            </el-form-item>
            <el-form-item label="经验要求" prop="experience_requirement">
              <el-select v-model="form.experience_requirement" placeholder="请选择">
                <el-option label="不限" value="none" />
                <el-option label="应届生" value="fresh" />
                <el-option label="1-3年" value="1-3" />
                <el-option label="3-5年" value="3-5" />
                <el-option label="5-10年" value="5-10" />
                <el-option label="10年以上" value="10+" />
              </el-select>
            </el-form-item>
            <el-form-item label="学历要求" prop="education_requirement">
              <el-select v-model="form.education_requirement" placeholder="请选择">
                <el-option label="不限" value="none" />
                <el-option label="高中" value="high_school" />
                <el-option label="大专" value="college" />
                <el-option label="本科" value="bachelor" />
                <el-option label="硕士" value="master" />
                <el-option label="博士" value="doctor" />
              </el-select>
            </el-form-item>
            <el-form-item label="职位类型" prop="job_type">
              <el-select v-model="form.job_type" placeholder="请选择">
                <el-option label="全职" value="full_time" />
                <el-option label="兼职" value="part_time" />
                <el-option label="实习" value="internship" />
                <el-option label="合同制" value="contract" />
              </el-select>
            </el-form-item>
            <el-form-item label="职位描述" prop="description">
              <el-input v-model="form.description" :rows="6" type="textarea" placeholder="职位职责、任职要求等" />
            </el-form-item>
            <el-form-item label="任职要求" prop="requirements">
              <el-input v-model="form.requirements" :rows="4" type="textarea" placeholder="技能要求、经验年限等" />
            </el-form-item>
            <el-form-item label="福利待遇" prop="benefits">
              <el-input v-model="form.benefits" :rows="4" type="textarea" placeholder="五险一金、补贴、假期等" />
            </el-form-item>
            <el-form-item label="招聘人数" prop="vacancy_count">
              <el-input-number v-model="form.vacancy_count" :min="1" :step="1" controls-position="right" />
            </el-form-item>
            <el-form-item label="过期时间" prop="expired_at">
              <el-input
                v-model="form.expired_at"
                placeholder="格式：YYYY-MM-DD，例如：2026-12-31"
                clearable
              />
            </el-form-item>
            <el-form-item label="状态" prop="status">
              <el-select v-model="form.status">
                <el-option label="开放中" value="published" />
                <el-option label="已关闭" value="closed" />
              </el-select>
            </el-form-item>
          </el-form>
          <template #footer>
            <div class="dialog-footer">
              <el-button size="large" @click="publishVisible = false">取消</el-button>
              <el-button type="primary" size="large" :loading="submitting" @click="submitPublish">确定发布</el-button>
            </div>
          </template>
        </el-dialog>
        <el-dialog 
          v-model="editVisible" 
          title="编辑职位" 
          width="720px" 
          destroy-on-close
          class="job-dialog"
        >
          <el-form :model="editForm" :rules="rules" ref="editFormRef" label-width="110px" class="job-form">
            <el-form-item label="职位名称" prop="title">
              <el-input v-model="editForm.title" placeholder="例如：前端开发工程师" />
            </el-form-item>
            <el-form-item label="工作城市" prop="work_city">
              <el-input v-model="editForm.work_city" placeholder="例如：北京" />
            </el-form-item>
            <el-form-item label="薪资范围" prop="salary_range">
              <el-select v-model="editForm.salary_range" placeholder="请选择">
                <el-option label="3k以下" value="3k以下" />
                <el-option label="3-5k" value="3-5k" />
                <el-option label="5-10k" value="5-10k" />
                <el-option label="10-15k" value="10-15k" />
                <el-option label="15-20k" value="15-20k" />
                <el-option label="20-30k" value="20-30k" />
                <el-option label="30-50k" value="30-50k" />
                <el-option label="50k以上" value="50k以上" />
              </el-select>
            </el-form-item>
            <el-form-item label="经验要求" prop="experience_requirement">
              <el-select v-model="editForm.experience_requirement" placeholder="请选择">
                <el-option label="不限" value="none" />
                <el-option label="应届生" value="fresh" />
                <el-option label="1-3年" value="1-3" />
                <el-option label="3-5年" value="3-5" />
                <el-option label="5-10年" value="5-10" />
                <el-option label="10年以上" value="10+" />
              </el-select>
            </el-form-item>
            <el-form-item label="学历要求" prop="education_requirement">
              <el-select v-model="editForm.education_requirement" placeholder="请选择">
                <el-option label="不限" value="none" />
                <el-option label="高中" value="high_school" />
                <el-option label="大专" value="college" />
                <el-option label="本科" value="bachelor" />
                <el-option label="硕士" value="master" />
                <el-option label="博士" value="doctor" />
              </el-select>
            </el-form-item>
            <el-form-item label="职位类型" prop="job_type">
              <el-select v-model="editForm.job_type" placeholder="请选择">
                <el-option label="全职" value="full_time" />
                <el-option label="兼职" value="part_time" />
                <el-option label="实习" value="internship" />
                <el-option label="合同制" value="contract" />
              </el-select>
            </el-form-item>
            <el-form-item label="职位描述" prop="description">
              <el-input v-model="editForm.description" :rows="6" type="textarea" placeholder="职位职责、任职要求等" />
            </el-form-item>
            <el-form-item label="任职要求" prop="requirements">
              <el-input v-model="editForm.requirements" :rows="4" type="textarea" placeholder="技能要求、经验年限等" />
            </el-form-item>
            <el-form-item label="福利待遇" prop="benefits">
              <el-input v-model="editForm.benefits" :rows="4" type="textarea" placeholder="五险一金、补贴、假期等" />
            </el-form-item>
            <el-form-item label="招聘人数" prop="vacancy_count">
              <el-input-number v-model="editForm.vacancy_count" :min="1" :step="1" controls-position="right" />
            </el-form-item>
            <el-form-item label="过期时间" prop="expired_at">
              <el-input
                v-model="editForm.expired_at"
                placeholder="格式：YYYY-MM-DD，例如：2026-12-31"
                clearable
              />
            </el-form-item>
            <el-form-item label="状态" prop="status">
              <el-select v-model="editForm.status">
                <el-option label="开放中" value="published" />
                <el-option label="已关闭" value="closed" />
              </el-select>
            </el-form-item>
          </el-form>
          <template #footer>
            <div class="dialog-footer">
              <el-button size="large" @click="editVisible = false">取消</el-button>
              <el-button type="primary" size="large" :loading="submitting" @click="submitEdit">确认</el-button>
            </div>
          </template>
        </el-dialog>
        <el-tabs v-model="activeTab" class="tabs">
          <el-tab-pane label="全部职位" name="all">
            <div v-if="jobsAll.length" class="jobs-list">
              <div v-for="job in jobsAll" :key="job.id" class="job-row">
                <div class="job-left">
                  <div class="job-title">
                    {{ job.title }}
                    <el-tag size="small" class="job-type-tag">{{ getJobTypeLabel(job.job_type) || '全职' }}</el-tag>
                  </div>
                  <div class="job-sub">
                    <el-tag v-if="job.work_city" size="small" class="info-tag">{{ job.work_city }}</el-tag>
                    <el-tag v-if="job.experience_requirement" size="small" class="info-tag">{{ getExperienceLabel(job.experience_requirement) }}</el-tag>
                    <el-tag v-if="job.education_requirement" size="small" class="info-tag">{{ getEducationLabel(job.education_requirement) }}</el-tag>
                    <el-tag v-if="job.salary_range" size="small" class="salary-tag">{{ job.salary_range || '薪资面议' }}</el-tag>
                  </div>
                </div>
                <div class="job-center">
                  <div class="metric"><div class="num">0</div><div class="txt">看过我</div></div>
                  <div class="metric"><div class="num">0</div><div class="txt">沟通过</div></div>
                  <div class="metric"><div class="num">0</div><div class="txt">感兴趣</div></div>
                </div>
                <div class="job-right">
                  <div class="status">
                    <span class="dot" :class="statusClass(normalizeStatus(job.status))"></span>
                    <span class="status-text">{{ displayStatus(job.status) }}</span>
                  </div>
                  <div class="actions">
                    <a class="action-link" @click="openEditDialog(job)">编辑</a>
                    <a class="action-link" @click="handleDeleteJob(job)">删除</a>
                    <a v-if="toggleActionText(job)" class="action-link" @click="handleToggleStatus(job)">{{ toggleActionText(job) }}</a>
                    <span class="more">···</span>
                  </div>
                </div>
              </div>
            </div>
            <div v-else class="empty"><el-empty description="没有相关数据" /></div>
          </el-tab-pane>
          <el-tab-pane label="开放中" name="open">
            <div v-if="jobsOpen.length" class="jobs-list">
              <div v-for="job in jobsOpen" :key="job.id" class="job-row">
                <div class="job-left">
                  <div class="job-title">
                    {{ job.title }}
                    <el-tag size="small" class="job-type-tag">{{ getJobTypeLabel(job.job_type) || '全职' }}</el-tag>
                  </div>
                  <div class="job-sub">
                    <el-tag v-if="job.work_city" size="small" class="info-tag">{{ job.work_city }}</el-tag>
                    <el-tag v-if="job.experience_requirement" size="small" class="info-tag">{{ getExperienceLabel(job.experience_requirement) }}</el-tag>
                    <el-tag v-if="job.education_requirement" size="small" class="info-tag">{{ getEducationLabel(job.education_requirement) }}</el-tag>
                    <el-tag v-if="job.salary_range" size="small" class="salary-tag">{{ job.salary_range || '薪资面议' }}</el-tag>
                  </div>
                </div>
                <div class="job-center">
                  <div class="metric"><div class="num">0</div><div class="txt">看过我</div></div>
                  <div class="metric"><div class="num">0</div><div class="txt">沟通过</div></div>
                  <div class="metric"><div class="num">0</div><div class="txt">感兴趣</div></div>
                </div>
                <div class="job-right">
                  <div class="status">
                    <span class="dot open"></span>
                    <span class="status-text">开放中</span>
                  </div>
                  <div class="actions">
                    <a class="action-link" @click="openEditDialog(job)">编辑</a>
                    <a class="action-link" @click="handleDeleteJob(job)">删除</a>
                    <a v-if="toggleActionText(job)" class="action-link" @click="handleToggleStatus(job)">{{ toggleActionText(job) }}</a>
                    <span class="more">···</span>
                  </div>
                </div>
              </div>
            </div>
            <div v-else class="empty"><el-empty description="没有相关数据" /></div>
          </el-tab-pane>
          <el-tab-pane label="待开放" name="pending" />
          <el-tab-pane label="审核失败" name="failed" />
          <el-tab-pane label="已关闭" name="closed">
            <div v-if="jobsClosed.length" class="jobs-list">
              <div v-for="job in jobsClosed" :key="job.id" class="job-row">
                <div class="job-left">
                  <div class="job-title">
                    {{ job.title }}
                    <el-tag size="small" class="job-type-tag">{{ getJobTypeLabel(job.job_type) || '全职' }}</el-tag>
                  </div>
                  <div class="job-sub">
                    <el-tag v-if="job.work_city" size="small" class="info-tag">{{ job.work_city }}</el-tag>
                    <el-tag v-if="job.experience_requirement" size="small" class="info-tag">{{ getExperienceLabel(job.experience_requirement) }}</el-tag>
                    <el-tag v-if="job.education_requirement" size="small" class="info-tag">{{ getEducationLabel(job.education_requirement) }}</el-tag>
                    <el-tag v-if="job.salary_range" size="small" class="salary-tag">{{ job.salary_range || '薪资面议' }}</el-tag>
                  </div>
                </div>
                <div class="job-center">
                  <div class="metric"><div class="num">0</div><div class="txt">看过我</div></div>
                  <div class="metric"><div class="num">0</div><div class="txt">沟通过</div></div>
                  <div class="metric"><div class="num">0</div><div class="txt">感兴趣</div></div>
                </div>
                <div class="job-right">
                  <div class="status">
                    <span class="dot closed"></span>
                    <span class="status-text">已关闭</span>
                  </div>
                  <div class="actions">
                    <a class="action-link" @click="openEditDialog(job)">编辑</a>
                    <a class="action-link" @click="handleDeleteJob(job)">删除</a>
                    <a v-if="toggleActionText(job)" class="action-link" @click="handleToggleStatus(job)">{{ toggleActionText(job) }}</a>
                    <span class="more">···</span>
                  </div>
                </div>
              </div>
            </div>
            <div v-else class="empty"><el-empty description="没有相关数据" /></div>
          </el-tab-pane>
        </el-tabs>
      </el-main>
    </el-container>
  </el-container>
</template>

<script setup>
import { reactive, ref, onMounted, onBeforeUnmount, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter } from 'vue-router'
import { fetchMainInfo, createJob, updateJob, toggleJobStatus, deleteJob } from '../src/api/enterprise.js'

const router = useRouter()
const user = reactive({ name: '', avatar: '', position: '' })
const companyInfo = ref(null)
const jobsAll = ref([])
const jobsOpen = computed(() => jobsAll.value.filter(j => {
  const s = normalizeStatus(j.status)
  return s === 'published' || s === 'open'
}))
const jobsClosed = computed(() => jobsAll.value.filter(j => {
  const s = normalizeStatus(j.status)
  return s === 'closed'
}))
const activeTab = ref('all')
const showUserCard = ref(false)
const userAreaRef = ref(null)
const userCardRef = ref(null)
const verified = ref(false)

// 发布职位弹窗与表单
const publishVisible = ref(false)
const submitting = ref(false)
const formRef = ref()
const form = reactive({
  title: '',
  work_city: '',
  salary_range: '10-15k',
  experience_requirement: 'none',
  education_requirement: 'none',
  job_type: 'full_time',
  description: '',
  requirements: '',
  benefits: '',
  vacancy_count: 1,
  expired_at: '',
  status: 'published',
})
const rules = {
  title: [{ required: true, message: '请输入职位名称', trigger: 'blur' }],
  work_city: [{ required: true, message: '请输入工作城市', trigger: 'blur' }],
  salary_range: [{ required: true, message: '请选择薪资范围', trigger: 'change' }],
  description: [{ required: true, message: '请输入职位描述', trigger: 'blur' }],
  vacancy_count: [{ required: true, message: '请输入招聘人数', trigger: 'change' }],
}

// 编辑职位弹窗与表单
const editVisible = ref(false)
const editFormRef = ref()
const currentJobId = ref(null)
const editForm = reactive({
  title: '',
  work_city: '',
  salary_range: '10-15k',
  experience_requirement: 'none',
  education_requirement: 'none',
  job_type: 'full_time',
  description: '',
  requirements: '',
  benefits: '',
  vacancy_count: 1,
  expired_at: '',
  status: 'published',
})

onMounted(async () => {
  await loadMainInfo()
  document.addEventListener('click', handleGlobalClick, true)
})

onBeforeUnmount(() => {
  document.removeEventListener('click', handleGlobalClick, true)
})

function toggleUserCard() {
  const next = !showUserCard.value
  showUserCard.value = next
  if (next) {
    // 打开卡片时刷新一次数据，确保状态最新
    loadMainInfo()
  }
}

function handleGlobalClick(e) {
  const area = userAreaRef.value
  const card = userCardRef.value
  if (!area) return
  const target = e.target
  const clickInside = area.contains(target)
  // 如果点击的是"所属企业"区域，不关闭卡片（因为会跳转）
  const isCompanyClick = target.closest('.uc-company')
  if (!clickInside && !isCompanyClick) {
    showUserCard.value = false
  }
}

function goAccount() {
  ElMessage.info('前往账号设置')
}

function goSecurity() {
  ElMessage.info('前往安全设置')
}

function goEnterprise() {
  ElMessage.info('前往企业认证')
}

function handleMenuSelect(index) {
  if (index === 'stats') {
    router.push('/enterprise/stats')
  }
  // 其他菜单项的处理可以在这里添加
}

function goCompanyInfo(e) {
  e.stopPropagation() // 阻止事件冒泡
  if (companyInfo.value) {
    // 将企业信息存储到sessionStorage，以便新页面使用
    sessionStorage.setItem('companyInfo', JSON.stringify(companyInfo.value))
    showUserCard.value = false // 关闭卡片
    router.push('/enterprise/company-info')
  } else {
    ElMessage.warning('暂无企业信息')
  }
}

function logout() {
  try {
    // 清除 Pinia 中的用户信息（如存在）
    // 兜底清理本地存储中的登录相关信息
    localStorage.removeItem('token')
    localStorage.removeItem('access')
    localStorage.removeItem('refresh')
    localStorage.removeItem('user')
    localStorage.removeItem('dingtalk_user_type')
  } catch (e) {
    // 忽略清理异常
  }

  ElMessage.success('已退出登录')
  showUserCard.value = false
  // 跳转到登录页
  router.replace('/login')
}

function normalizeStatus(status) {
  if (!status) return ''
  const s = String(status).toLowerCase()
  if (s.includes('publish') || status === '已发布' || status === '开放中') return 'published'
  if (s.includes('close') || status === '已关闭' || status === '关闭' || status === '已失效') return 'closed'
  if (status === '待开放' || s.includes('pending')) return 'pending'
  if (status === '审核失败' || s.includes('failed')) return 'failed'
  return s
}

function displayStatus(status) {
  const s = normalizeStatus(status)
  if (s === 'published') return '开放中'
  if (s === 'closed') return '已关闭'
  if (s === 'pending') return '待开放'
  if (s === 'failed') return '审核失败'
  return status || '—'
}

function statusClass(s) {
  if (s === 'published' || s === 'open') return 'open'
  if (s === 'closed') return 'closed'
  if (s === 'pending') return 'pending'
  if (s === 'failed') return 'failed'
  return ''
}

function toggleActionText(job) {
  const s = normalizeStatus(job?.status)
  if (s === 'published' || s === 'open') return '关闭'
  if (s === 'closed') return '打开'
  return ''
}

function getJobTypeLabel(value) {
  if (!value) return '全职'
  const map = {
    'full_time': '全职',
    'part_time': '兼职',
    'internship': '实习',
    'contract': '合同制',
    '全职': '全职',
    '兼职': '兼职',
    '实习': '实习',
    '合同制': '合同制'
  }
  return map[value] || value
}

function getExperienceLabel(value) {
  if (!value) return '经验不限'
  const map = {
    'none': '经验不限',
    'fresh': '应届生',
    '1-3': '1-3年',
    '3-5': '3-5年',
    '5-10': '5-10年',
    '10+': '10年以上'
  }
  return map[value] || value
}

function getEducationLabel(value) {
  if (!value) return '学历不限'
  const map = {
    'none': '学历不限',
    'high_school': '高中',
    'college': '大专',
    'bachelor': '本科',
    'master': '硕士',
    'doctor': '博士'
  }
  return map[value] || value
}

async function handleToggleStatus(job) {
  if (!job || !job.id) {
    ElMessage.warning('职位信息无效')
    return
  }
  try {
    const token = localStorage.getItem('token') || ''
    await toggleJobStatus(job.id, token)
    ElMessage.success('状态切换成功')
    await loadMainInfo()
  } catch (e) {
    console.error('切换状态失败:', e)
    const errorMsg = e?.response?.data?.error || '切换失败'
    ElMessage.error(errorMsg)
  }
}

async function handleDeleteJob(job) {
  if (!job || !job.id) {
    ElMessage.warning('职位信息无效')
    return
  }
  
  try {
    await ElMessageBox.confirm(
      `确定要删除职位"${job.title}"吗？此操作不可恢复。`,
      '确认删除',
      {
        confirmButtonText: '确定删除',
        cancelButtonText: '取消',
        type: 'warning',
        confirmButtonClass: 'el-button--danger',
        center: true
      }
    )
    
    const token = localStorage.getItem('token') || ''
    await deleteJob(job.id, token)
    ElMessage.success('职位已删除')
    await loadMainInfo()
  } catch (e) {
    // 用户取消删除
    if (e === 'cancel') {
      return
    }
    console.error('删除职位失败:', e)
    const errorMsg = e?.response?.data?.error || '删除失败'
    ElMessage.error(errorMsg)
  }
}

function openPublishDialog() {
  publishVisible.value = true
}

function resetForm() {
  form.title = ''
  form.work_city = ''
  form.salary_range = '10-15k'
  form.experience_requirement = 'none'
  form.education_requirement = 'none'
  form.job_type = 'full_time'
  form.description = ''
  form.requirements = ''
  form.benefits = ''
  form.vacancy_count = 1
  form.expired_at = ''
  form.status = 'published'
}

function submitPublish() {
  if (!formRef.value) return
  formRef.value.validate(async (valid) => {
    if (!valid) return
    try {
      submitting.value = true
      const token = localStorage.getItem('token') || ''
      const payload = { ...form }
      
      // 处理日期格式：如果 expired_at 存在且不为空，确保格式正确
      if (payload.expired_at && payload.expired_at.trim() !== '') {
        const dateStr = payload.expired_at.trim()
        if (/^\d{4}-\d{2}-\d{2}$/.test(dateStr)) {
          payload.expired_at = `${dateStr}T23:59:59Z`
        }
      } else {
        payload.expired_at = null
      }
      
      await createJob(payload, token)
      ElMessage.success('职位发布成功')
      publishVisible.value = false
      resetForm()
      await loadMainInfo()
    } catch (e) {
      ElMessage.error(e?.response?.data?.error || '发布失败')
    } finally {
      submitting.value = false
    }
  })
}

// 将中文值转换为英文值的映射函数
function normalizeJobType(value) {
  if (!value) return 'full_time'
  const map = {
    '全职': 'full_time',
    '兼职': 'part_time',
    '实习': 'internship',
    '合同制': 'contract',
    'full_time': 'full_time',
    'part_time': 'part_time',
    'internship': 'internship',
    'contract': 'contract'
  }
  return map[value] || value
}

function normalizeExperienceRequirement(value) {
  if (!value) return 'none'
  const map = {
    '不限': 'none',
    '应届生': 'fresh',
    '1-3年': '1-3',
    '3-5年': '3-5',
    '5-10年': '5-10',
    '10年以上': '10+',
    'none': 'none',
    'fresh': 'fresh',
    '1-3': '1-3',
    '3-5': '3-5',
    '5-10': '5-10',
    '10+': '10+'
  }
  return map[value] || value
}

function normalizeEducationRequirement(value) {
  if (!value) return 'none'
  const map = {
    '不限': 'none',
    '高中': 'high_school',
    '大专': 'college',
    '本科': 'bachelor',
    '硕士': 'master',
    '博士': 'doctor',
    'none': 'none',
    'high_school': 'high_school',
    'college': 'college',
    'bachelor': 'bachelor',
    'master': 'master',
    'doctor': 'doctor'
  }
  return map[value] || value
}

// 将日期格式转换为 YYYY-MM-DD 格式（用于日期选择器）
function normalizeDate(dateValue) {
  if (!dateValue) return ''
  // 如果是 ISO 格式（如 "2026-12-31T23:59:59Z"），提取日期部分
  if (typeof dateValue === 'string') {
    // 处理 ISO 格式：2026-12-31T23:59:59Z 或 2026-12-31T23:59:59.000Z
    if (dateValue.includes('T')) {
      return dateValue.split('T')[0]
    }
    // 如果已经是 YYYY-MM-DD 格式，直接返回
    if (/^\d{4}-\d{2}-\d{2}$/.test(dateValue)) {
      return dateValue
    }
  }
  return dateValue
}

function openEditDialog(job) {
  if (!job || !job.id) {
    ElMessage.warning('职位信息无效')
    return
  }
  currentJobId.value = job.id
  // 填充表单数据，将可能的中文值转换为英文值
  editForm.title = job.title || ''
  editForm.work_city = job.work_city || ''
  editForm.salary_range = job.salary_range || '10-15k'
  editForm.experience_requirement = normalizeExperienceRequirement(job.experience_requirement) || 'none'
  editForm.education_requirement = normalizeEducationRequirement(job.education_requirement) || 'none'
  editForm.job_type = normalizeJobType(job.job_type) || 'full_time'
  editForm.description = job.description || ''
  editForm.requirements = job.requirements || ''
  editForm.benefits = job.benefits || ''
  editForm.vacancy_count = job.vacancy_count || 1
  // 处理日期格式：将 ISO 格式转换为 YYYY-MM-DD
  editForm.expired_at = normalizeDate(job.expired_at) || ''
  editForm.status = normalizeStatus(job.status) || 'published'
  editVisible.value = true
}

function submitEdit() {
  if (!editFormRef.value) return
  editFormRef.value.validate(async (valid) => {
    if (!valid) return
    if (!currentJobId.value) {
      ElMessage.error('职位ID不存在')
      return
    }
    try {
      submitting.value = true
      const token = localStorage.getItem('token') || ''
      const payload = { ...editForm }
      
      // 处理日期格式：如果 expired_at 存在且不为空，确保格式正确
      if (payload.expired_at && payload.expired_at.trim() !== '') {
        // 如果只是日期格式 YYYY-MM-DD，转换为 ISO 格式
        const dateStr = payload.expired_at.trim()
        if (/^\d{4}-\d{2}-\d{2}$/.test(dateStr)) {
          payload.expired_at = `${dateStr}T23:59:59Z`
        } else {
          // 如果已经是 ISO 格式，保持不变
          // 如果格式不正确，保持原值（让后端验证）
        }
      } else {
        // 如果为空，设置为 null（如果后端不接受空字符串）
        payload.expired_at = null
      }
      
      console.log('提交的编辑数据:', payload)
      console.log('职位ID:', currentJobId.value)
      await updateJob(currentJobId.value, payload, token)
      ElMessage.success('职位更新成功')
      editVisible.value = false
      currentJobId.value = null
      await loadMainInfo()
    } catch (e) {
      console.error('更新职位失败:', e)
      console.error('错误详情:', e?.response?.data)
      
      // 处理错误信息
      let errorMsg = '更新失败'
      if (e?.response?.data) {
        if (e.response.data.details) {
          // 如果有详细的验证错误，显示第一个错误
          const details = e.response.data.details
          if (typeof details === 'object') {
            const firstError = Object.values(details)[0]
            errorMsg = Array.isArray(firstError) ? firstError[0] : firstError
          } else {
            errorMsg = details
          }
        } else if (e.response.data.error) {
          errorMsg = e.response.data.error
        }
      }
      
      ElMessage.error(errorMsg)
    } finally {
      submitting.value = false
    }
  })
}

async function loadMainInfo() {
  try {
    const token = localStorage.getItem('token') || ''
    const data = await fetchMainInfo(token)
    if (data && data.user_info) {
      user.name = data.user_info.name || ''
      user.avatar = data.user_info.avatar || ''
      user.position = data.user_info.position || ''
    }
    // 保存企业信息
    if (data && data.company_info) {
      companyInfo.value = data.company_info
    }
    // 保存岗位列表
    if (Array.isArray(data?.job_list)) {
      jobsAll.value = data.job_list
    } else {
      jobsAll.value = []
    }
    // 兼容多种结构路径
    // 根据后端返回结构（见 www.txt）：is_verified 在 company_info 下
    const candidates = [
      data && data.company_info && data.company_info.is_verified,
      data && data.is_verified,
      data && data.enterprise && data.enterprise.is_verified,
      data && data.user_info && data.user_info.is_verified,
      data && data.data && data.data.is_verified,
    ]
    const flag = candidates.find((v) => v !== undefined && v !== null)
    const normalize = (v) => {
      if (v === true || v === 1 || v === '1') return true
      if (typeof v === 'string' && v.toLowerCase && v.toLowerCase() === 'true') return true
      return false
    }
    verified.value = normalize(flag)
  } catch (e) {
    ElMessage.error(e?.response?.data?.error || '加载失败')
  }
}
</script>

<style scoped>
.layout {
  height: 100vh;
}
.topbar {
  display: flex;
  align-items: center;
  padding: 0 16px;
  background: #fff;
  border-bottom: 1px solid #eef0f3;
}
.gray-text {
  color: #999;
}
.brand {
  font-size: 18px;
  font-weight: 600;
}
.spacer { flex: 1; }
.user-info { display: flex; align-items: center; gap: 25px; position: relative; }
.user-name { color: #333; cursor: pointer; transition: color .2s; }
.user-name.active { color: #00c293; font-weight: 600; }

.user-card {
  position: absolute;
  top: 56px;
  right: 0;
  width: 240px;
  background: #fff;
  border: 1px solid #eef0f3;
  border-radius: 12px;
  box-shadow: 0 12px 32px rgba(0,0,0,.08);
  overflow: hidden;
  z-index: 1000;
}
.user-card-header {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 14px 16px;
  background: linear-gradient(90deg,#f6fffb 0%, #ffffff 100%);
}
.uc-head { display: flex; flex-direction: column; gap: 4px; flex: 1; }
.uc-name { font-weight: 600; color: #333; }
.uc-pos { font-size: 12px; color: #666; }
.uc-company {
  display: flex;
  align-items: center;
  gap: 4px;
  cursor: pointer;
  padding: 4px 8px;
  border-radius: 6px;
  transition: all 0.2s;
  margin-left: auto;
}
.uc-company:hover {
  background: rgba(0, 194, 147, 0.1);
}
.uc-company-text {
  font-size: 12px;
  color: #666;
  white-space: nowrap;
}
.uc-arrow {
  width: 12px;
  height: 12px;
  color: #999;
  transition: transform 0.2s;
  flex-shrink: 0;
}
.uc-company:hover .uc-arrow {
  color: #00c293;
  transform: translateX(2px);
}
.uc-item-row { display: flex; align-items: center; justify-content: space-between; }
.uc-status { font-size: 12px; display: inline-flex; align-items: center; gap: 6px; }
.uc-status.ok { color: #00c293; font-weight: 600; }
.uc-status.pending { color: #999; }
.uc-icon { width: 16px; height: 16px; }
.user-card-body { display: grid; }
.uc-item {
  padding: 12px 16px;
  cursor: pointer;
  color: #333;
}
.uc-item:hover { background: #f7f9fb; }
.user-card-footer { border-top: 1px solid #f0f2f5; }
.uc-logout { padding: 12px 16px; color: #ff4d4f; cursor: pointer; }
.uc-logout:hover { background: #fff1f0; }
.sidebar { border-right: 1px solid #eef0f3; }
.content { background: #fafbfc; }

.tabs {
  margin-top: 16px;
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.04);
  overflow: hidden;
}
.tabs :deep(.el-tabs__header) {
  margin: 0;
  padding: 0 24px;
  background: #fff;
  border-bottom: 1px solid #f0f2f5;
}
.tabs :deep(.el-tabs__nav-wrap::after) { display: none; }
.tabs :deep(.el-tabs__item) {
  height: 56px;
  line-height: 56px;
  font-size: 14px;
  font-weight: 500;
  color: #666;
}
.tabs :deep(.el-tabs__item:hover) { color: #333; }
.tabs :deep(.el-tabs__item.is-active) {
  color: #00c293;
  font-weight: 600;
}
.tabs :deep(.el-tabs__active-bar) {
  background: #00c293;
  height: 3px;
  border-radius: 3px 3px 0 0;
}
.tabs :deep(.el-tabs__content) { padding: 0; }

.job-row {
  display: flex;
  align-items: center;
  padding: 20px 24px;
  border-bottom: 1px solid #f0f2f5;
  transition: background 0.2s;
}
.job-row:hover { background: #fafbfc; }
.job-left { flex: 1; min-width: 0; }
.job-title {
  font-size: 16px;
  font-weight: 600;
  color: #333;
  margin-bottom: 8px;
  display: flex;
  align-items: center;
  gap: 8px;
}
.job-type-tag {
  height: 20px;
  line-height: 18px;
  padding: 0 6px;
  font-size: 12px;
  border-radius: 4px;
  background: #f0f2f5;
  color: #666;
  border: none;
}
.job-sub {
  display: flex;
  align-items: center;
  gap: 8px;
  flex-wrap: wrap;
}
.info-tag, .salary-tag {
  height: 20px;
  line-height: 18px;
  padding: 0 6px;
  font-size: 12px;
  border-radius: 4px;
  border: none;
}
.info-tag {
  background: #f0f8ff;
  color: #666;
}
.salary-tag {
  background: #fff7e6;
  color: #fa8c16;
}
.job-center {
  display: flex;
  align-items: center;
  gap: 24px;
  margin: 0 48px;
}
.metric {
  display: flex;
  flex-direction: column;
  align-items: center;
  min-width: 56px;
}
.metric .num {
  font-size: 16px;
  font-weight: 600;
  color: #333;
  line-height: 1.2;
}
.metric .txt {
  font-size: 12px;
  color: #999;
  line-height: 1.2;
}
.job-right {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  gap: 12px;
  min-width: 140px;
}
.status {
  display: flex;
  align-items: center;
  gap: 6px;
}
.dot {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background: #999;
}
.dot.open { background: #00c293; }
.dot.closed { background: #999; }
.dot.pending { background: #faad14; }
.dot.failed { background: #ff4d4f; }
.status-text {
  font-size: 12px;
  color: #666;
}
.actions {
  display: flex;
  align-items: center;
  gap: 12px;
}
.action-link {
  font-size: 12px;
  color: #00c293;
  text-decoration: none;
  cursor: pointer;
}
.action-link:hover { text-decoration: underline; }
.more {
  font-size: 14px;
  color: #999;
  cursor: pointer;
  padding: 0 4px;
}
.empty {
  padding: 80px 0;
  text-align: center;
}

.job-dialog {
  border-radius: 12px;
  overflow: hidden;
}
.job-dialog :deep(.el-dialog__header) {
  padding: 20px 28px;
  border-bottom: 1px solid #f0f2f5;
}
.job-dialog :deep(.el-dialog__title) {
  font-size: 18px;
  font-weight: 600;
  color: #333;
}
.job-dialog :deep(.el-dialog__body) {
  padding: 24px 28px;
  max-height: 60vh;
  overflow-y: auto;
}
.job-dialog :deep(.el-dialog__footer) {
  padding: 0;
}

:deep(.job-form .el-form-item) {
  margin-bottom: 20px;
}
:deep(.job-form .el-form-item__label) {
  font-weight: 500;
  color: #333;
  line-height: 1.5;
}
:deep(.job-form .el-input__wrapper) {
  border-radius: 8px;
  box-shadow: 0 0 0 1px #e5e7eb inset;
  transition: all 0.2s;
}
:deep(.job-form .el-input__wrapper:hover) {
  box-shadow: 0 0 0 1px #00c293 inset;
}
:deep(.job-form .el-input__wrapper.is-focus) {
  box-shadow: 0 0 0 2px #00c293 inset;
}
:deep(.job-form .el-textarea__inner) {
  border-radius: 8px;
  box-shadow: 0 0 0 1px #e5e7eb inset;
  transition: all 0.2s;
}
:deep(.job-form .el-textarea__inner:hover) {
  box-shadow: 0 0 0 1px #00c293 inset;
}
:deep(.job-form .el-textarea__inner:focus) {
  border-color: #00c293;
  box-shadow: 0 0 0 3px rgba(0, 194, 147, 0.1);
}

:deep(.job-form .el-input-number) {
  width: 100%;
}

:deep(.job-form .el-input-number .el-input__wrapper) {
  border-radius: 8px;
}

:deep(.dialog-footer) {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  padding: 20px 28px;
  border-top: 1px solid #f0f2f5;
  background: #fafbfc;
}

:deep(.dialog-footer .el-button) {
  min-width: 100px;
  height: 40px;
  border-radius: 8px;
  font-weight: 500;
  transition: all 0.2s;
}

:deep(.dialog-footer .el-button--primary) {
  background: linear-gradient(135deg, #00c293 0%, #00a58a 100%);
  border: none;
  box-shadow: 0 2px 8px rgba(0, 194, 147, 0.25);
}

:deep(.dialog-footer .el-button--primary:hover) {
  background: linear-gradient(135deg, #00a58a 0%, #008f7a 100%);
  box-shadow: 0 4px 12px rgba(0, 194, 147, 0.35);
  transform: translateY(-1px);
}

:deep(.dialog-footer .el-button:not(.el-button--primary)) {
  background: #fff;
  border: 1px solid #e5e7eb;
  color: #6b7280;
}

:deep(.dialog-footer .el-button:not(.el-button--primary):hover) {
  border-color: #00c293;
  color: #00c293;
  background: #f0fffd;
}
</style>
<!--</template>-->